import GoodsDiv from '@/components/GoodsDiv';
import RightFixed from '@/layouts/RightFixed';
import TopBread from '@/layouts/TopBread';
import { isPushHome, selectByName } from '@/services/commodity';
import { getAllWrite } from '@/services/write';
import { colorStr } from '@/utils/utils';
import { Input, Menu } from 'antd';
import moment from 'moment';
import { useCallback, useEffect, useState } from 'react';
import { history } from 'umi';
import CarouselImg from './components/CarouselImg';
import styles from './index.less';

const ShopPage: React.FC = () => {
  // 主题颜色的值
  const [color, setColor] = useState<string>(localStorage.getItem('color') || '#1a7721');
  const [pushHomeList, setPushHomeList] = useState<any[]>([]);
  const [pushImgList, setPushImgList] = useState<any[]>([]);
  const [noticeList, setNoticeList] = useState<any[]>([]);
  // const [pageSize, setPageSize] = useState(10);
  const [selectList, setSelectList] = useState<any[]>([]);
  let isNotLogin = !localStorage.getItem('qs');
  // let typeObj = {
  //   1: 'tagsOne',
  //   2: 'tagsTwo',
  //   3: 'tagsThree',
  //   4: 'tagsFour',
  // };
  const { Search } = Input;
  const svgTop: React.CSSProperties = {
    height: '26px',
    color: color,
    textAlign: 'center',
  };

  const getPushList = useCallback(async () => {
    try {
      await isPushHome({ pageSize: 100 }).then((res) => {
        let arrHome: any = [];
        let arrImg: any = [];
        res.list.map((item: any) => {
          if (item.ispush === '1') {
            let current = JSON.stringify(item.img)
              .replace('[', '')
              .replace(']', '')
              .replace(/"/g, '')
              .replace(/\\/g, '')
              .split(',');

            arrImg.push({ ...item, img: current[0] });
          } else {
            arrHome.push(item);
          }
        });
        setPushHomeList(arrHome);
        setPushImgList(arrImg);
      });
    } catch (error) {
      console.log(error);
    }
  }, []);

  const getNoticeList = useCallback(async () => {
    try {
      await getAllWrite({ pageIndex: 1, pageSize: 8 }).then((res) => {
        setNoticeList(res.list);
      });
    } catch (error) {
      console.log(error);
    }
  }, []);

  useEffect(() => {
    getNoticeList();
  }, [getNoticeList]);

  useEffect(() => {
    getPushList();
  }, [getPushList]);

  const selectGoodsByName = async (value: string) => {
    try {
      await selectByName({ title: value, pageSize: 10, pageIndex: 1 }).then((res) => {
        setSelectList(res.list);
      });
    } catch (error) {
      console.log(error);
    }
  };

  const onSearch = (value: string) => {
    selectGoodsByName(value);
    isNotLogin
      ? history.push('/login&register')
      : history.push({
          pathname: '/goodsPage',
          query:
            value !== ''
              ? { lastRoute: '商城首页', titleValue: value, listByName: selectList }
              : { lastRoute: '商城首页' },
        });
  };

  return (
    <div className={styles.container}>
      <TopBread lastRoute={'网站登录'} now={'商城首页'} setColorParent={setColor} />
      <div className={styles.contentStyle}>
        <div className={styles.content}>
          <div className={styles.search}>
            <div
              className={styles.pageLogo}
              style={{ textShadow: `0 0 0.5em ${color}, 0 0 0.2em #5c5c5c` }}
            >
              四季养生
            </div>
            <div className={styles.svgs}>
              <img src={require('@/assets/images/安全保障.svg')} alt={'加载失败'} style={svgTop} />
              <span style={{ marginRight: 10 }}>安全保障</span>
              <img src={require('@/assets/images/包邮.svg')} alt={'加载失败'} style={svgTop} />
              <span style={{ marginRight: 10 }}>一件包邮</span>
              <img src={require('@/assets/images/退货保障.svg')} alt={'加载失败'} style={svgTop} />
              <span style={{ marginRight: 528 }}>退货保障</span>
            </div>
            <div>
              <Search
                placeholder="请输入想要购买的商品"
                onSearch={onSearch}
                style={{
                  width: 391,
                  border: `1px solid ${color}`,
                  borderRadius: 6,
                  color: `${color}`,
                }}
              />
            </div>
          </div>
          <div className={styles.imgNotice}>
            <CarouselImg color={color} pushImgList={pushImgList === null ? [] : pushImgList} />
            <div className={styles.notice} style={{ border: `1px solid ${colorStr(2)}` }}>
              <div
                className={styles.noticeTop}
                style={{
                  borderBottom: `1px solid ${colorStr(8)}`,
                }}
              >
                养生小专栏
              </div>
              <div className={styles.noticeContent}>
                {noticeList.map((item) => (
                  <div
                    key={item.id}
                    className={styles.notices}
                    onClick={() => {
                      isNotLogin
                        ? history.push('/login&register')
                        : history.push({
                            pathname: './write',
                            query: { lastRoute: '商城首页', id: item.id },
                          });
                    }}
                  >
                    <div className={styles.noticeTitle}>{item.title}</div>
                    <div>{moment(Number(item.timeadd)).format('YYYY-MM-DD')}</div>
                  </div>
                ))}
              </div>
              <div className={styles.noticeBottom} style={{ color: colorStr(9) }}>
                <img src={require('@/assets/images/查看更多.svg')} alt={'加载失败'} />
                <div
                  className={styles.getMore}
                  onClick={() => {
                    isNotLogin
                      ? history.push('/login&register')
                      : history.push({
                          pathname: '/advice',
                          query: { lastRoute: '商城首页' },
                        });
                  }}
                >
                  查看更多
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className={styles.otherContent}>
          <Menu
            mode="horizontal"
            className={styles.menuStyle}
            style={{
              background: colorStr(6),
              border: 0,
              height: 58,
              fontSize: 18,
              padding: '4px 41px',
            }}
            defaultSelectedKeys={['0']}
          >
            <Menu.Item key={'0'}>网站推荐</Menu.Item>
            <Menu.Item
              key={'1'}
              onClick={() => {
                isNotLogin
                  ? history.push('/login&register')
                  : history.push({
                      pathname: '/goodsPage',
                      query: { lastRoute: '商城首页' },
                    });
              }}
            >
              所有商品
            </Menu.Item>
          </Menu>

          <GoodsDiv goods={pushHomeList === null ? [] : pushHomeList} ifHomePage={'1'} />
          <div className={styles.bottomLoading}>
            {/* {pushHomeList.length < pageSize ? ( */}
            <span style={{ color: color, fontWeight: 600 }}>
              快点击上方的所有商品去查看全部商品吧！
            </span>
            {/* ) : (
              <></>
              // <Button 
              //   onClick={() => {
              //     setPageSize(pageSize + 5);
              //   }}
              //   style={{ background: colorStr(4), color: '#fff', height: 50 }}
              // >
              //   查看更多商品
              // </Button>*/}
            {/* // )} */}
          </div>
          {/* <div>
            <div className={styles.lable}>
              {typeArr.map((item) => {
                let transform = typeObj[Math.floor(Math.random() * 4) + 1];
                return (
                  <div className={styles[transform]} key={item.value}>
                    <Tag
                      color={colorCount[Math.floor(Math.random() * colorCount.length)]}
                      style={{
                        fontSize: Math.random() * 20,
                        position: 'relative',
                        left: `${Math.random() * 70}%`,
                        top: Math.random() * 40,
                      }}
                    >
                      {item.label}
                    </Tag>
                  </div>
                );
              })}
            </div>
            <Button
              className={styles.buyBtn}
              style={{ backgroundColor: colorStr(4) }}
              onClick={() => {
                isNotLogin
                  ? history.push('/login&register')
                  : history.push({
                      pathname: '/goodsPage',
                      query: { lastRoute: '商城首页' },
                    });
              }}
            >
              前去购买所有商品
            </Button>
          </div> */}
        </div>
      </div>
      <RightFixed color={color} thisRoute={'商城首页'} />
    </div>
  );
};
export default ShopPage;
